﻿var rootGuid = '00000000000000000000000000000000';
var targetCategory = null;
var clientGuid = guid();
var widgets = new Array();

var jQT = new $.jQTouch({
	addGlossToIcon: false,
	statusBar: 'black',
	fullScreen: true,
	icon: 'images/jqtouch.png',
	startupScreen: 'images/jqt_startup.png',
	preloadImages: [
		'images/back_button.png',
		'images/back_button_clicked.png',
		'images/button_clicked.png',
		'images/grayButton.png',
		'images/whiteButton.png',
		'images/loading.gif',
		'images/close.gif'
		]
	});

$(document).ready(function() {
	buildInterface();
});

function buildInterface()
{
	$.ajaxSetup({
		cache: false,
		timeout: 10000,
		error: function(XMLHttpRequest, textStatus, errorThrown){
			$("#errorMessage").text("Error Connecting Server");
			$('#errorPane').makeFloaty({
				spacing: 20, time: '1s'
			});
		}
	});
	
	$("#errorPane").hideFloaty();
	
	$("#closeErrorPane").click(function(){
        $("#errorPane").hideFloaty();
        $(this).removeClass('active');
        return false;
    });
    
    $("#addCategoryButton").click(function(){
		$.ajax({
			type: "GET",
			url: "/s/addCategory",
			data: {parentGuid : targetCategory, categoryName : $("#categoryName").val(), sortOrder : $("#categorySortOrder").val(), isWidgetGroup : false},
			success: function(data){
				if(!data)
				{
					$("#errorMessage").text("Error adding category!");
					$('#errorPane').makeFloaty({
						spacing: 20, time: '1s'
					});
				}
				else
				{
					window.location.reload(true);
				}
			}
		});
    });
    
    $("#addWidgetButton").click(function(){
   
		$.ajax({
			type: "GET",
			url: "/s/addWidget",
			data: {parentGuid : targetCategory, widgetName : $("#widgetName").val(), sortOrder : $("#widgetSortOrder").val(), widgetTypeId : $("#widgetTypeId").val(), valueGuid : $("#addWidgetValueList").val()},
			success: function(data){
				if(!data)
				{
					$("#errorMessage").text("Error adding widget!");
					$('#errorPane').makeFloaty({
						spacing: 20, time: '1s'
					});
				}
				else
				{
					window.location.reload(true);
				}
			}
		});
    });

    $("#addWidgetGroupButton").click(function(){
		$.ajax({
			type: "GET",
			url: "/s/addCategory",
			data: {parentGuid : targetCategory, categoryName : $("#widgetGroupName").val(), sortOrder : $("#widgetGroupSortOrder").val(), isWidgetGroup : true},
			success: function(data){
				if(!data)
				{
					$("#errorMessage").text("Error adding widget group!");
					$('#errorPane').makeFloaty({
						spacing: 20, time: '1s'
					});
				}
				else
				{
					window.location.reload(true);
				}
			}
		});
    });
	
	$.ajax({
		type: "GET",
		url: "/s/getInterface",
		success: function(data){
			eval('var categories=(' + data + ')');
			
			buildInterfaceRecursive(categories);
			
			jQT.goTo('#' + rootGuid);
		},
	});
	
	$.ajax({
		type: "GET",
		url: "/s/getComPort",
		success: function(data){
			$("#comPort").val(data);
			
			$("#comPort").bind('change', function() {						
				$.ajax({
					type: "GET",
					url: "/s/setComPort",
					data: {value : $(this).val()}
				});
			});
		}
	});
	
	$.ajax({
		type: "GET",
		url: "/s/getServerAddress",
		success: function(data){
			$("#serverHost").val(data);
			
			$("#serverHost").bind('change', function() {						
				$.ajax({
					type: "GET",
					url: "/s/setServerAddress",
					data: {value : $(this).val()}
				});
			});
		}
	});
	
	$.arte({
		'time':5000, 
		'ajax_mode': 'GET',
		'ajax_type': 'json',
		'ajax_url' : '/s/getNotifications',
		'on_data_set' : function() {
			return "clientGuid=" + clientGuid;
		},
		'on_success' : function(data) {
			eval('var notifications=(' + data + ')');	
			
			for ( var i = 0; i < notifications.length; i++ )
			{
				var notification = notifications[i];
			
				if (notification.Type == "ValueChanged")
				{
				    widgets[notification.WidgetTypeId].valueChanged(notification);
				}
			}
		}
	}).start();
	
	for (var widget in widgets){
	    $("#widgetTypeId").append("<option value='" + widgets[widget].widgetTypeId + "'>" + widgets[widget].optionText + "</option>");
    }
}

function edit(cat)
{
	$('#addCategory_' + cat).show();
	$('#addWidgetGroup_' + cat).show();
	$('#done_' + cat).show();
	
	$('.widgetGroupText').show();
	$('.widgetGroupDelete').show();
	$('.widgetGroupAdd').show();
	$('.widgetGroupLabel').hide();

	$('.widgetText').show();
	$('.widgetDelete').show();
	$('.widgetAdd').show();
	$('.widgetLabel').hide();
	
	if(cat != rootGuid) 
	{
	    $('#deleteCategory_' + cat).show();
	    $('#headingCategoryName_' + cat).show();
	    $('#headingCategoryLabel_' + cat).hide();
    }
    
    $('#edit_' + cat).hide();
}

function doneEditing(cat)
{
	$('#addCategory_' + cat).hide();
	$('#addWidgetGroup_' + cat).hide();
	$('#deleteCategory_' + cat).hide();

    $('#headingCategoryName_' + cat).hide();
    $('#headingCategoryLabel_' + cat).show();

    $('.widgetGroupText').hide();
    $('.widgetGroupDelete').hide();
    $('.widgetGroupAdd').hide();
	$('.widgetGroupLabel').show();
	
    $('.widgetText').hide();
    $('.widgetDelete').hide();
    $('.widgetAdd').hide();
	$('.widgetLabel').show();

	$('#done_' + cat).hide();	
	$('#edit_' + cat).show();
}

function addCategory(cat)
{
	targetCategory = cat;
	$("#categoryName").val("");
	$("#categorySortOrder").val("");
}

function addWidgetGroup(cat)
{
	targetCategory = cat;
	$("#widgetGroupName").val("");
	$("#widgetGroupSortOrder").val("");
}

function addWidget(cat)
{
	targetCategory = cat;
	$("#widgetName").val("");
	$("#addWidgetValueList").empty();
	
	$.ajax({
		type: "GET",
		url: "/s/getValues",
		success: function(data){
			eval('var values=(' + data + ')');	
			
			for ( var i = 0; i < values.length; i++ )
			{
				var value = values[i];
			
                $("#addWidgetValueList").append("<option value='" + value.ValueGuid + "'>" + value.NodeId + "-" + value.DeviceLabel + " - " + value.Label + "</option>");
			}
		}
	});
}

function changeCategoryName(catGuid, categoryName, labelObject)
{
	$.ajax({
		type: "GET",
		url: "/s/changeCategoryName",
		data: {categoryGuid : catGuid, categoryName : categoryName},
		success: function() {
			labelObject.text(categoryName);
			$('#lnk_' + catGuid).text(categoryName);
		}
	});
}

function changeWidgetName(widGuid, widgetName, labelObject)
{
	$.ajax({
		type: "GET",
		url: "/s/changeWidgetName",
		data: {widgetGuid : widGuid, widgetName : widgetName},
		success: function() {
			labelObject.text(widgetName);
		}
	});
}

function deleteCategory(catGuid)
{
	$.ajax({
		type: "GET",
		url: "/s/deleteCategory",
		data: {categoryGuid : catGuid},
		success: function() {
			window.location.reload(true);
		}
	});
}

function deleteWidget(widGuid)
{
	$.ajax({
		type: "GET",
		url: "/s/deleteWidget",
		data: {widgetGuid : widGuid},
		success: function() {
			window.location.reload(true);
		}
	});
}

function buildInterfaceRecursive(cat)
{
	var categoryHtml = '';
	var catGuid = cat.CategoryGuid.replace(/-/g,'');
	
	categoryHtml = categoryHtml + "<div id='" + catGuid + "' ";

	categoryHtml = categoryHtml + "><div class='toolbar'>";
	
	categoryHtml = categoryHtml + "<input type='text' class='headingText' id='headingCategoryName_" + catGuid + "' value='" + cat.Label + "' />";
	categoryHtml = categoryHtml + "<h1 id='headingCategoryLabel_" + catGuid + "'>" + cat.Label + "</h1>";

	if (cat.CategoryGuid.replace(/-/g,'') != rootGuid)
	{
		categoryHtml = categoryHtml + "<a class='back' href='#'>Back</a>";
	}
	else
	{
		categoryHtml = categoryHtml + "<a class='button leftButton flip' href='#settings'>Settings</a>";	
	}
	
	categoryHtml = categoryHtml + "<a class='button' id='edit_" + catGuid + "' href='#'>Edit</a>";
	categoryHtml = categoryHtml + "<a class='button' style='display: none' id='done_" + catGuid + "' href='#'>Done</a>";
	
	categoryHtml = categoryHtml + "</div><ul class='rounded'>";
	
	for ( var i = 0; i < cat.Children.length; i++ )
	{
		var subCategory = cat.Children[i];
		var subCatGuid = subCategory.CategoryGuid.replace(/-/g,'');
		
		if (subCategory.IsWidgetGroup) // Widget group
		{
			categoryHtml = categoryHtml + "<li><table width='100%' border='0'><tr><td colspan='2' align='center'>";
			
			//Delete button
			categoryHtml = categoryHtml + "<a href='#' class='deleteButton widgetGroupDelete' id='widgetGroupDelete_" + subCatGuid + "'>Del</a>";
			//Title textbox
			categoryHtml = categoryHtml + "<input type='text' class='headingText widgetGroupText' id='headingWidgetGroupName_" + subCatGuid + "' value='" + subCategory.Label + "' />";
			//Title label
			categoryHtml = categoryHtml + "<span class='widgetGroupLabel' id='headingWidgetGroupLabel_" + subCatGuid + "'>" + subCategory.Label + "</span>";
			//Add button
			categoryHtml = categoryHtml + "<a href='#addWidget' class='addButton widgetGroupAdd' id='widgetAdd_" + subCatGuid + "'>+</a>";
			
			categoryHtml = categoryHtml + "<hr/></td></tr>";
			
			for ( var j = 0; j < subCategory.Widgets.length; j++ )
			{
				var widget = subCategory.Widgets[j];
				var widGuid = widget.WidgetGuid.replace(/-/g,'');
				
				categoryHtml = categoryHtml + "<tr><td>";

				//Delete button
    			categoryHtml = categoryHtml + "<a href='#' class='deleteButton widgetDelete' id='widgetDelete_" + widGuid + "'>Del</a>";
    			//Title textbox
    			categoryHtml = categoryHtml + "<input type='text' class='widgetText' id='headingWidgetName_" + widGuid + "' value='" + widget.Label + "' />";
			    //Title label
			    categoryHtml = categoryHtml + "<span class='widgetLabel' id='headingWidgetLabel_" + widGuid + "'>" + widget.Label + "</span>";
				
				categoryHtml = categoryHtml + "</td><td align='right'>";
				
				categoryHtml = categoryHtml + widgets[widget.WidgetTypeId].getHtml(widget);
				
				categoryHtml = categoryHtml + "<br/></td></tr>";
			}
			
			categoryHtml = categoryHtml + "</table></li>";
		}
		else
		{
			categoryHtml = categoryHtml + "<li class='arrow'><img id='deleteCategory' alt=''/><a id='lnk_" + subCatGuid + "' href='#" + subCatGuid + "'>" + subCategory.Label + "</a><small class='counter'>" + subCategory.Children.length + "</small></li>";

			buildInterfaceRecursive(subCategory);
		}
	}
	
	categoryHtml = categoryHtml + "</ul>";
	
	categoryHtml = categoryHtml + "<a id='addCategory_" + catGuid + "' href='#addCategory' style='margin: 10px;display: none;' class='whiteButton slideup'>Add Sub Category</a>";
	categoryHtml = categoryHtml + "<a id='addWidgetGroup_" + catGuid + "' href='#addWidgetGroup' style='margin: 10px;display: none;' class='whiteButton slideup'>Add Widget Group</a>";
	categoryHtml = categoryHtml + "<a id='deleteCategory_" + catGuid + "' href='#' style='margin: 10px;display: none;' class='redButton slideup'>Delete Category</a>";
	
	categoryHtml = categoryHtml + "<div class='info'><p><strong>HomeWave</strong></p></div></div>";
	
	$('#jqt').prepend(categoryHtml);
		
	$('#edit_' + cat.CategoryGuid.replace(/-/g,'')).bind('click', {catGuid: catGuid}, function(event) {
		edit(event.data.catGuid);
		return false;
	});
	
	$('#done_' + cat.CategoryGuid.replace(/-/g,'')).bind('click', {catGuid: catGuid}, function(event) {
		doneEditing(event.data.catGuid);
		return false;
	});
	
	$('#addCategory_' + catGuid).bind('click', {catGuid: catGuid}, function(event) {
		addCategory(event.data.catGuid);
	});
	
	$('#addWidgetGroup_' + catGuid).bind('click', {catGuid: catGuid}, function(event) {
		addWidgetGroup(event.data.catGuid);
	});
	
	$('#deleteCategory_' + catGuid).bind('click', {catGuid: catGuid}, function(event) {
		deleteCategory(event.data.catGuid);
	});
	
	$('#headingCategoryName_' + catGuid).bind('change', {catGuid: catGuid}, function(event) {
		changeCategoryName(event.data.catGuid, $(this).val(), $('#headingCategoryLabel_' + event.data.catGuid));
	});
	
	for ( var i = 0; i < cat.Children.length; i++ )
	{
		var subCategory = cat.Children[i];
		var subCategoryGuid = subCategory.CategoryGuid.replace(/-/g,'');
		
		if (subCategory.IsWidgetGroup)
		{
			$('#headingWidgetGroupName_' + subCategoryGuid).bind('change', {catGuid: subCategoryGuid}, function(event) {
		        changeCategoryName(event.data.catGuid, $(this).val(), $('#headingWidgetGroupLabel_' + event.data.catGuid));
	        });
	        
            $('#widgetGroupDelete_' + subCategoryGuid).bind('click', {catGuid: subCategoryGuid}, function(event) {
		        deleteCategory(event.data.catGuid);
	        });
	        
	        $('#widgetAdd_' + subCategoryGuid).bind('click', {catGuid: subCategoryGuid}, function(event) {
		        addWidget(event.data.catGuid);
	        });
		}
		
		for ( var j = 0; j < subCategory.Widgets.length; j++ )
		{
			var widget = subCategory.Widgets[j];
            var widGuid = widget.WidgetGuid.replace(/-/g,'');
            
			$('#headingWidgetName_' + widGuid).bind('change', {widGuid: widGuid}, function(event) {
		        changeWidgetName(event.data.widGuid, $(this).val(), $('#headingWidgetLabel_' + event.data.widGuid));
	        });
	        
            $('#widgetDelete_' + widGuid).bind('click', {widGuid: widGuid}, function(event) {
		        deleteWidget(event.data.widGuid);
	        });
	        
	        widgets[widget.WidgetTypeId].widgetReady(widget);
		}
	};
}


function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

function guid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

function dumpProps(obj, parent) {
   // Go through all the properties of the passed-in object 
   for (var i in obj) {
	  // if a parent (2nd parameter) was passed in, then use that to 
	  // build the message. Message includes i (the object's property name) 
	  // then the object's property value on a new line 
	  if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
	  // Display the message. If the user clicks "OK", then continue. If they 
	  // click "CANCEL" then quit this level of recursion 
	  if (!confirm(msg)) { return; }
	  // If this property (i) is an object, then recursively process the object 
	  if (typeof obj[i] == "object") { 
		 if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
	  }
   }
}
				
function renderJSON(obj) {
	var keys = []
	var retValue = ""
	for (var key in obj) {
			if(typeof obj[key] == 'object') {
					retValue += "<div class='tree'>" + key                                          
					retValue += renderJSON(obj[key])
					retValue += "</div>"
			}
			else {
					retValue += "<div class='tree'>" + key + " = " + obj[key] + "</div>"
			}

	   keys.push(key)
	}
	return retValue;
}